<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
                >
    
    <xsl:output method="xml"
                encoding="UTF-8"
                indent="yes"
    />
    
    <!-- key for generating distinct years (Muenchian grouping) -->
    <xsl:key name="kTransactionYear" match="/iati-activities/iati-activity/transaction/transaction-date" use="substring(@iso-date, 1,4)"/>
            
    <!-- matches root element of iati xml documents --> 
    <xsl:template match="iati-activities">
        <!-- insert country code for better identification (ID of country) -->
        <country code="{//recipient-country/@code}">
            <name>
                <!-- full name of country -->
                <xsl:value-of select="//recipient-country/text()"/>
            </name> 
            
            <!-- selectring only transaction-dates with distinct year 
                 each year will be selcted only once -->
            <xsl:apply-templates select="/iati-activities/iati-activity/transaction/transaction-date[generate-id()
                                                                        =
                                                                        generate-id(key('kTransactionYear', substring(@iso-date, 1,4))[1])
                                                                    ]"/>
        </country>
    </xsl:template>
    
    <!-- matches transactions -->
    <xsl:template match="transaction-date">
        <!-- abbreviation of organization to which transaction belong -->
        <xsl:variable name="org">
            <!-- there are only two of them -->
            <xsl:choose>
                <xsl:when test="../../contact-info/organisation/text()='The World Bank'">TWB</xsl:when>
                <xsl:otherwise>UNDP</xsl:otherwise>
            </xsl:choose>
        </xsl:variable>

        <!-- year of transacation -->
        <xsl:variable name="year" select="substring(./@iso-date,1,4)"/>

        <!-- generates element with sum of all transaction values which occured in given year -->
        <transaction year="{$year}" organization="{$org}" currency="{../../@default-currency}">
            <xsl:value-of select="format-number(sum(/iati-activities/iati-activity/transaction[substring(./transaction-date/@iso-date,1,4) = $year]/value), '0')"/>
        </transaction>
    </xsl:template>
    
</xsl:stylesheet>
